/**
 * @date   2011-5-8
 * @author tianye
 */
package cn.edu.dlut.WingGame.IOsystem;

import android.view.KeyEvent;
import cn.edu.dlut.WingGame.BaseType.ObjectState;
import cn.edu.dlut.WingGame.Object.WingObject;
import cn.edu.dlut.WingGame.Tools.ObjectContainer;

public class WingKeyboard {
	public static boolean isKeyDown = false;
	public static int KeyCode;
	public static KeyEvent mEvent;
	private static ObjectContainer mObjects = new ObjectContainer();

	public static boolean onKeyDown(int keyCode, KeyEvent event) { // 按键事件处理
		mEvent = event;
		isKeyDown = true;
		KeyCode = keyCode;
		return postDownMessage(keyCode, event);
	}

	public static boolean onKeyUp(int keyCode, KeyEvent event) {
		mEvent = event;
		isKeyDown = false;
		KeyCode = keyCode;
		return postUpMessage(keyCode, event);
	}

	public static void addKeyListener(WingObject obj) {
		mObjects.addObject(obj);
	}

	public static void delKeyListener(int id) {
		mObjects.delObjectByID(id);
	}

	public static void delKeyListener(String name) {
		WingObject obj;
		for (int i = 0; i < mObjects.getSize(); i++) {
			obj = mObjects.getObject(i);
			if (obj.mName == name) {
				mObjects.delObjectByID(obj.mID);
				break;
			}
		}
	}

	private static boolean postDownMessage(int keyCode, KeyEvent event) {
		WingObject obj;
		for (int i = 0; i < mObjects.getSize(); i++) {
			obj = mObjects.getObject(i);
			if (obj.getState() != ObjectState.stop)
				((KeyListener) obj).onKeyDown(keyCode, event);
		}
		return true;
	}

	private static boolean postUpMessage(int keyCode, KeyEvent event) {
		WingObject obj;
		for (int i = 0; i < mObjects.getSize(); i++) {
			obj = mObjects.getObject(i);
			if (obj.getState() != ObjectState.stop)
				((KeyListener) obj).onKeyUp(keyCode, event);
		}
		return true;
	}
}
